  import { WebSocketGateway, SubscribeMessage, MessageBody, ConnectedSocket, WebSocketServer } from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';

@WebSocketGateway({ cors: { origin: '*' } })
export class WebsocketGateway {
  @WebSocketServer()
  server: Server;

  private userSocketMap = new Map<string, string>(); // 用户ID -> Socket ID

  // 用户连接时绑定ID
  @SubscribeMessage('setUser')
  handleSetUser(@MessageBody() userId: string, @ConnectedSocket() client: Socket) {
    console.log(`用户 ${userId} 已连接，Socket ID: ${client.id}`);
    this.userSocketMap.set(userId, client.id);
    client.data.userId = userId; // 存储用户ID到socket实例
     this.server.to(client.id).emit('success', {
         msg:
          "成功"
        })
    return `用户 ${userId} 已连接，Socket ID: ${client.id}`
  }

  // 处理断开连接
  handleDisconnect(client: Socket) {
    const userId = client.data.userId;
    if (userId) {
      console.log(`用户 ${userId} 已断开连接`);
      this.userSocketMap.delete(userId);
    }
  }

  // 处理单聊消息
  @SubscribeMessage('newMessage')
  handleMessage(
    @MessageBody() body: { targetUserId: string; content: string },
    @ConnectedSocket() client: Socket
  ) {
    console.log(`收到来自用户 ${client.data.userId} 的消息，目标用户: ${body.targetUserId}`);
    const targetSocketId = this.userSocketMap.get(body.targetUserId);
    if (targetSocketId) {
      console.log(`向用户 ${body.targetUserId} 发送消息 ${body.content}`);
      this.server.to(targetSocketId).emit('onMessage', {
        senderId: client.data.userId, // 发送者ID
        content: body.content
      });
    } else {
      console.log(`用户 ${body.targetUserId} 不在线`);
      client.emit('error', '对方当前不在线');
    }
  }

    // 处理大屏连接消息
    @SubscribeMessage('bigScreen')
    handleBigMessage() {
        this.server.emit('bigScreenMessage', "连接成功");
      return "连接成功"
    }
}